/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yongw.MouseMove;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.swing.SwingUtilities;

/**
 * 主程序
 * @author 张永伟
 */
public class MouseMove extends Application {
    private TextArea ta; 
    private String way = "蓝牙方式";
    private Button btnSure = new Button("确定");
    private Text txtHostMsg = new Text("");
    private Text txtNotfMsg = new Text("您的电脑没有蓝牙，请使用wifi方式连接！");
    private Text txtAutoMsg = new Text("10秒后将自动开启连接，当前选择:蓝牙方式！");
    private Button btnNotfMsgSure = new Button("我知道了");
    Stage primaryStage, stageChoose,stageMessage, stageHelp, stageAbout, stageDonate;
       
    RadioButton rb0 = new RadioButton("wifi方式2");
    RadioButton rb1 = new RadioButton("wifi方式"); 
    RadioButton rb2 = new RadioButton("蓝牙方式");
    VBox vbox_primary, vbox1;
    boolean selected = false;
    TrayIcon trayIcon ;
    JavaServer serverThreadClass;
    MenuBar menuBar;
    HBox root_hbox;
    
    /**
     *主程序入口
     * @param primaryStage 主界面
     */
    @Override
    public void start(Stage primaryStage) {        
        this.primaryStage = primaryStage;
        initPrimaryStage();
        intiStageChoose();
        initStageMessage();
        initStageAbout();
        initStageHelp();
        initStageDonate();
        stageChoose.show();
        
        btnSure.setOnAction(e -> {
            selected = true;
            txtAutoMsg.setText("当前选择:" + way );
            startServer();
        });
        btnSure.requestFocus();
        
        btnNotfMsgSure.setOnAction(e ->{
            stageMessage.close();
            stageChoose.show();
        });    
        new Thread(new autoStart()).start();
    }
    
    /**
     * 初始化主界面
     */
    private void initPrimaryStage(){
        //初始化菜单栏       
        menuBar = new MenuBar();
        Menu menuSwitch = new Menu("切换至");
        Menu menuViewHelp = new Menu("帮助");
        Menu menuViewDonate = new Menu();
        Label lbDonate = new Label("打赏");
        menuViewDonate.setGraphic(lbDonate);
        lbDonate.setOnMouseClicked(e -> {            
            stageDonate.show();
        });
        menuBar.getMenus().addAll(menuSwitch,menuViewHelp, menuViewDonate);
        javafx.scene.control.MenuItem itemViewHelp = new javafx.scene.control.MenuItem("帮助");
        javafx.scene.control.MenuItem itemViewAbout = new javafx.scene.control.MenuItem("关于");
        menuViewHelp.getItems().addAll(itemViewHelp, itemViewAbout);
        javafx.scene.control.MenuItem itemViewWifi = new javafx.scene.control.MenuItem("wifi方式");
        javafx.scene.control.MenuItem itemViewBlueth = new javafx.scene.control.MenuItem("蓝牙方式");
        javafx.scene.control.MenuItem itemViewWifi2 = new javafx.scene.control.MenuItem("wifi方式2");
        menuSwitch.getItems().addAll(itemViewWifi, itemViewBlueth,itemViewWifi2);
        itemViewHelp.setOnAction(e -> {
            stageHelp.show();
        });
        itemViewAbout.setOnAction(e -> {
            stageAbout.show();            
        });
        itemViewWifi.setOnAction(e ->{
            if(!way.equals("wifi方式"))
                changeServer("wifi方式");
        });
        itemViewBlueth.setOnAction(e -> {
            if(!way.equals("蓝牙方式"))
                changeServer("蓝牙方式");
        });
        itemViewWifi2.setOnAction(e ->{
            if(!way.equals("wifi方式2"))
                changeServer("wifi方式2");
        });
        ta = new TextArea(); 
        StackPane root = new StackPane();
        root.getChildren().add(ta);        
        ta.setPrefRowCount(100); 
        ImageView imageview_ewm = new ImageView(new javafx.scene.image.Image(this.getClass().getResource("ewm.jpg").toString()));
        imageview_ewm.setFitWidth(150);
        imageview_ewm.setFitHeight(150);
        root_hbox = new HBox(10);        
        VBox vbox_ewm = new VBox(5);
        Label lbl_formal = new Label("安卓端正式版获取:\n华为应用市场搜索'无线鼠标'");
        vbox_ewm.getChildren().addAll(new Label("安卓端体验版应用获取:\n使用浏览器扫描下方二维码下载"),imageview_ewm, lbl_formal);
        vbox_ewm.setAlignment(Pos.CENTER);
        root_hbox.getChildren().addAll(vbox_ewm, root);
        vbox_primary = new VBox(10);
        vbox_primary.setAlignment(Pos.CENTER);
        vbox_primary.getChildren().addAll(menuBar, txtHostMsg, root_hbox);
        Scene scene = new Scene(vbox_primary, 700, 400);
        primaryStage.setScene(scene);
        primaryStage.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        primaryStage.setOnCloseRequest((WindowEvent event) -> {
            SystemTray tray = SystemTray.getSystemTray();      
            Platform.setImplicitExit(false);
            primaryStage.hide();
            try {
                tray.add(this.trayIcon);
              //  trayIcon.displayMessage("notification", "I am here", TrayIcon.MessageType.INFO);
            } catch (AWTException ex) {
                Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
            }          
        });
        primaryStage.iconifiedProperty().addListener(e -> {
            SystemTray tray = SystemTray.getSystemTray();      
            Platform.setImplicitExit(false);
            if(primaryStage.isIconified()){ //是最小化操作
                primaryStage.hide();
                try {
                    tray.add(this.trayIcon);                    
                } catch (AWTException ex) {
                    Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
                }
            }            
        });
        //初始化状态栏
        initTray();
    }
    /**
     * 初始化选择方式窗口
     */
    private void intiStageChoose(){
        stageChoose = new Stage();
        stageChoose.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        BorderPane rootPane = new BorderPane();
        final ToggleGroup group = new ToggleGroup();
        rb0.setToggleGroup(group);
        rb1.setToggleGroup(group);
        rb2.setToggleGroup(group);
        rb2.setSelected(true);
        rb0.setUserData("wifi方式2");
        rb1.setUserData("wifi方式");
        rb2.setUserData("蓝牙方式");     
        group.selectedToggleProperty().addListener(e -> {
            if(group.getSelectedToggle() != null){
                selected= true;
                way = group.getSelectedToggle().getUserData().toString();
                txtAutoMsg.setText("当前选择:" + way );
            }
        });
        
        HBox hbox = new HBox(10);
        hbox.getChildren().add(rb0);
        hbox.getChildren().add(rb1);
        hbox.getChildren().add(rb2);
        vbox1 = new VBox(10);
        vbox1.getChildren().addAll(new Text("请选择和手机端的连接方式"),hbox, btnSure);
        btnSure.setAlignment(Pos.BOTTOM_RIGHT);
        hbox.setAlignment(Pos.CENTER);
        vbox1.setAlignment(Pos.CENTER);
        rootPane.setCenter(vbox1);        
        rootPane.setBottom(txtAutoMsg);
        BorderPane.setAlignment(txtAutoMsg, Pos.CENTER);
        
        Scene scene1 = new Scene(rootPane, 300, 200);
        stageChoose.setScene(scene1);
        stageChoose.setTitle("无线鼠标电脑端");
        stageChoose.setOnCloseRequest((WindowEvent event) -> {
            selected = true;
        });
    }
    /**
     * 初始化通知信息窗口
     */
    private void initStageMessage(){
        stageMessage = new Stage();
        stageMessage.setTitle("通知");
        stageMessage.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        VBox vbox_noti = new VBox(5);
        vbox_noti.getChildren().addAll(txtNotfMsg, btnNotfMsgSure);
        vbox_noti.setAlignment(Pos.CENTER);
        Scene scene2 = new Scene(new StackPane(vbox_noti), 300, 200);
        stageMessage.setScene(scene2);
    }
    /**
     * 初始化关于窗口
     */
    private void initStageAbout() {
        stageAbout = new Stage();
        stageAbout.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        BorderPane rootPane = new BorderPane();
        GridPane gridpane = new GridPane();
        gridpane.setAlignment(Pos.CENTER);
        Text textUrl = new Text(" https://gitee.com/zhangyongwei11/mousemove/");
        TextField tfMail = new TextField("805151765@qq.com");
        textUrl.setFill(Color.BLUE);
        textUrl.setUnderline(true);
        tfMail.setEditable(false);
        tfMail.setStyle("-fx-background-insets:0;-fx-bakcground-color:transparent, white, transparent, white;");
        Button btnDonate = new Button("鼓励一下");
        btnDonate.setFont(new Font(20));
        gridpane.add(new Text("软件名称："), 0, 0);
        gridpane.add(new Text("无线鼠标电脑端"), 1 ,0);
        gridpane.add(new Text("软件版本："), 0, 1);
        gridpane.add(new Text("V1.2.0"), 1, 1);
        gridpane.add(new Text("作   者："), 0, 2);
         gridpane.add(new Text("鱆鱼尾"), 1, 2);
        gridpane.add(new Text("联系作者:"), 0, 3);
        gridpane.add(tfMail, 1, 3);
         gridpane.add(new Text("下载地址："), 0, 4);
         gridpane.add(textUrl, 1, 4);
        btnDonate.requestFocus();
         textUrl.setOnMouseClicked(e -> {
             new Thread(() -> {
                 try {
                    Desktop.getDesktop().browse(new URI("https://gitee.com/zhangyongwei11/mousemove/"));
                } catch (URISyntaxException ex) {
                    Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
                }
             }).start();            
         });
        BorderPane.setAlignment(btnDonate, Pos.CENTER);
        BorderPane.setAlignment(gridpane, Pos.CENTER);
        rootPane.setCenter(gridpane);
        rootPane.setBottom(btnDonate);
        
        btnDonate.setOnAction(e -> {
            //鼓励一下作者打赏
            stageDonate.show();
        });
        Scene sceneAbout = new Scene(rootPane, 400, 200);
        stageAbout.setScene(sceneAbout);
    }
    /**
     * 初始化帮助窗口
     */
    private void initStageHelp() {
        stageHelp = new Stage();
        stageHelp.setTitle("帮助");
        stageHelp.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        BorderPane rootPane = new BorderPane();
        
        File helpFile = new File("lib/help.txt");
        VBox vbox = new VBox(2);        
        String temp1 = "";
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(helpFile), "UTF-8"));
            String temp = br.readLine();
            while(temp !=null){
               // temp = new String(temp.getBytes(), "gbk");                   
                if(temp.contains(".")){
                    if(temp1!=""){
                        TextArea txtcontext = new TextArea(temp1);
                        txtcontext.setFont(new Font(16));
                        int height = 40 * temp1.length()/20;
                        if(temp.contains("wifi") && temp.contains("2."))
                            height = 360;                       
                        txtcontext.setMaxSize(380, height);
                        txtcontext.setMinHeight(height);
                        txtcontext.setEditable(false);
                        txtcontext.setWrapText(true);
                        vbox.getChildren().add(txtcontext);
                        temp1="";
                    }
                    TextArea txtTitle = new TextArea(temp);
                    txtTitle.setFont(new Font(16));
                    int height =40* temp.length()/22 < 40?40:40* temp.length()/22;
                    txtTitle.setMaxSize(380, height);
                    txtTitle.setMinHeight(height);
                    txtTitle.setEditable(false);
                    txtTitle.setWrapText(true);
                    vbox.getChildren().add(txtTitle);                    
                }else{
                    temp1+=temp + "\n";    
                }
                temp = br.readLine();  
            }
            if(temp1!=""){
                TextArea txtcontext = new TextArea(temp1);
                txtcontext.setFont(new Font(16));
                int height = 40 * temp1.length()/20;
                txtcontext.setMaxSize(380, height);
                txtcontext.setEditable(false);
                txtcontext.setWrapText(true);
                vbox.getChildren().add(txtcontext);
            }
            br.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
        }   
        Button btClose = new Button("关闭");
        BorderPane.setAlignment(btClose, Pos.CENTER);
        rootPane.setCenter(new ScrollPane(vbox));
        rootPane.setBottom(btClose);
        btClose.setOnAction(e -> stageHelp.close());
        Scene sceneHelp = new Scene(rootPane, 400, 600);
        stageHelp.setScene(sceneHelp);
    }
    /**
     * 初始化状态栏图标
     */
    private void initTray(){
        Image image = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("Logo_TrayIcon.png"));        
        PopupMenu popup= new PopupMenu();
        trayIcon= new TrayIcon(image, "无线鼠标电脑端",popup);
        trayIcon.setImageAutoSize(true);
        MouseAdapter trayIconMouseAdapter = new MouseAdapter(){
            public void mouseClicked(MouseEvent e){
                if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount()==2){
                    Platform.runLater(() -> {
                    try{
                        if(primaryStage.isIconified())
                            primaryStage.setIconified(false);
                        if(!primaryStage.isShowing())
                            primaryStage.show();
                        }catch(Exception ex){
                            ex.printStackTrace();
                           // trayIcon.displayMessage("notification", "I am here", TrayIcon.MessageType.WARNING);
                        }
                        SystemTray.getSystemTray().remove(trayIcon);
                         primaryStage.toFront();
                    });     
                }else if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount()==1){
                   // trayIcon.displayMessage("infotitle", "info", TrayIcon.MessageType.INFO);
                }
            }
        };
        trayIcon.addMouseListener(trayIconMouseAdapter);       
        
        MenuItem showItem = new MenuItem("显示窗口");
        MenuItem exitItem = new MenuItem("退出");
        popup.add(showItem);
        popup.add(exitItem);
        showItem.addActionListener( e -> {            
            Platform.runLater(() -> {
                try{
                if(primaryStage.isIconified())
                    primaryStage.setIconified(false);
                if(!primaryStage.isShowing())
                    primaryStage.show();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
                SystemTray.getSystemTray().remove(trayIcon);
                 primaryStage.toFront();
            });            
        });
        exitItem.addActionListener(e -> {
            System.exit(1);
        });
       
    }
    /**
     * 开始服务器
     */
    private void startServer(){
        if(way.equals("蓝牙方式")){                
            primaryStage.setTitle("无线鼠标电脑端(蓝牙方式)");    
            if(vbox_primary.getChildren().contains(txtHostMsg))
                vbox_primary.getChildren().remove(txtHostMsg);
            try{
                serverThreadClass = new BluetoothJavaServer(ta);
                new Thread(serverThreadClass).start();
                primaryStage.show();
            }catch(Exception ex){
                txtNotfMsg.setText("蓝牙方式启动失败,原因:"+ex.getMessage()+"。\n请选用其他方式!");
                stageMessage.show();   
            }                
            stageChoose.close();                
        }else if(way.equals("wifi方式")){
            primaryStage.setTitle("无线鼠标电脑端(Wifi方式)"); 
            txtHostMsg.setText("本机IP为:" );
            txtHostMsg.setFont(new Font(24));
            if(!vbox_primary.getChildren().contains(txtHostMsg)){
                vbox_primary.getChildren().clear();
                vbox_primary.getChildren().addAll(menuBar, txtHostMsg, root_hbox);
            }
            try{
                serverThreadClass = new WifiJavaServer(ta, txtHostMsg);
                new Thread(serverThreadClass).start();
                primaryStage.show();
              //  stageDonate.show();
            }catch(Exception ex){
                txtNotfMsg.setText("无线启动方式失败,原因:"+ex.getMessage()+"。\n请确保电脑已连接至无线网络或选用其他方式!");
                stageMessage.show();
                primaryStage.close();                    
            }                
            stageChoose.close();                
        }else if(way.equals("wifi方式2")){
            primaryStage.setTitle("无线鼠标电脑端(Wifi方式2)"); 
            txtHostMsg.setText("本机IP为:" );
            txtHostMsg.setFont(new Font(24));
            if(!vbox_primary.getChildren().contains(txtHostMsg)){
                vbox_primary.getChildren().clear();
                vbox_primary.getChildren().addAll(menuBar, txtHostMsg, root_hbox);
            }
            try{
                serverThreadClass = new WifiJavaServer2(ta, txtHostMsg);
                new Thread(serverThreadClass).start();
                primaryStage.show();
              //  stageDonate.show();
            }catch(Exception ex){
                txtNotfMsg.setText("无线启动方式失败,原因:"+ex.getMessage()+"。\n请确保电脑已连接至无线网络或选用其他方式!");
                stageMessage.show();
                primaryStage.close();                    
            }                
            stageChoose.close();     
        }
    }
    /**
     * 切换服务器
     */
    private void changeServer(String targetWay){
        serverThreadClass.closeServer();
        ta.clear();        
        way = targetWay;
        if(way.equals("wifi方式")){
            rb1.setSelected(true);
        }else if(way.equals("蓝牙方式")){
            rb2.setSelected(true);
        }else
            rb0.setSelected(true);
        startServer();       
    }
    /**
     * 初始化打赏界面
     */
    private void initStageDonate() {
        stageDonate = new Stage();
        stageDonate.getIcons().add(new javafx.scene.image.Image(getClass().getResourceAsStream("Logo_TrayIcon.png")));
        stageDonate.setTitle("创作不易，打赏一块吧");
        BorderPane rootPane = new BorderPane();
        HBox hbox = new HBox(10);
        VBox vbox1 = new VBox(5);
        VBox vbox2 = new VBox(5);
        ImageView imageview1 = new ImageView(new javafx.scene.image.Image(this.getClass().getResource("wx.png").toString()));
        imageview1.setFitHeight(150);
        imageview1.setFitWidth(150);        
        ImageView imageview2 = new ImageView(new javafx.scene.image.Image(this.getClass().getResource("zfb.jpg").toString()));
        imageview2.setFitHeight(150);
        imageview2.setFitWidth(150);
        vbox1.getChildren().addAll(new Text("微  信"), imageview1);
        vbox1.setAlignment(Pos.CENTER);
        vbox2.getChildren().addAll(new Text("支付宝"), imageview2);
        vbox2.setAlignment(Pos.CENTER);        
        hbox.getChildren().addAll(vbox1, vbox2);
        Button btClose = new Button("关闭");
        rootPane.setBottom(btClose);
        rootPane.setCenter(hbox);
        BorderPane.setAlignment(hbox, Pos.CENTER);
        BorderPane.setAlignment(btClose, Pos.CENTER);
        btClose.setOnAction(e -> stageDonate.close());
        Scene sceneDonate = new Scene(rootPane, 310, 250);
        stageDonate.setScene(sceneDonate);
    }
    /**
     * 实现自动开启服务器的类
     */    
    private class autoStart implements Runnable {
        @Override
        public void run() {
            int times  = 10;
            while(true){
                times--;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(times == 0 || selected)
                    break;
                final int restSecond = times;
                Platform.runLater(() -> {
                    txtAutoMsg.setText(restSecond + "秒后将自动开启连接，当前选择:蓝牙方式！");
                });
            }
            if(times == 0){
                Platform.runLater(() -> {
                    startServer();
                    txtAutoMsg.setText("当前选择:" + way);
                });                
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);    
    }   
   
}
